import service from "@/utils/http";

/**
 * 获取图书列表
 * @param {Object} params - 查询参数 { pagenum, pagesize, type, bookName, number }
 * @returns {Promise} Axios Promise
 */
export const getBookListAPI = (params) => {
  return service({
    url: '/api/book/list',
    method: 'get',
    params
  })
}

/**
 * 添加图书
 * @param {Object} bookData - 图书数据 
 * @returns {Promise} Axios Promise
 */
export const addBookAPI = (bookData) => {
  const formData = new FormData();
  
  // 必填字段
  const requiredFields = [
    'number', 'bookName', 'type', 'author', 
    'price', 'language', 'location', 'publisher'
  ];
  
  requiredFields.forEach(field => {
    formData.append(field, bookData.get(field));
  });
  
  // 可选字段
  if (bookData.get('cover')) {
    formData.append('cover', bookData.get('cover'));
  }
  
  return service({
    url: '/api/book/add',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
}

/**
 * 删除图书
 * @param {number|string} id - 图书ID
 * @returns {Promise} Axios Promise
 */
export const deleteBookAPI = (id) => {
  return service({
    url: '/api/book/del',
    method: 'delete',
    params: { id }
  })
}

/**
 * 更新图书信息
 * @param {Object} bookData - 图书数据 
 * @returns {Promise} Axios Promise
 */
export const updateBookAPI = (bookData) => {
  const formData = new FormData();
  
  // 必填字段
  const requiredFields = [
    'number', 'bookName', 'type', 'author', 
    'price', 'language', 'location', 'publisher', 'id'
  ];
  
  requiredFields.forEach(field => {
    if (bookData.get(field)) {
      formData.append(field, bookData.get(field));
    }
  });
  
  // 可选字段
  if (bookData.get('cover')) {
    formData.append('cover', bookData.get('cover'));
  }
  
  return service({
    url: '/api/book/put',
    method: 'put',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
}

/**
 * 获取图书详情
 * @param {number|string} id - 图书ID
 * @returns {Promise} Axios Promise
 */
export const getBookDetailsAPI = (id) => {
  return service({
    url: '/api/book/det',
    method: 'get',
    params: { id }
  });
}